<template>
  <div>
    <div class="sku-title">尺码表</div>
    <a-row style="margin-top: 15px;">
      <a-button type="primary" @click="handleSave">保存尺码表方案</a-button>
      <j-search-select-tag type="list" v-model="skuSizeTableSchemeId" :dictOptions="skuSizeTableSchemeOptions" placeholder="请选择尺码表方案"  style="margin: 0 8px; width: 10%;" @change="handleChange"/>
      <a-button type="danger" @click="handleDelete" v-if="skuSizeTableSchemeId">删除方案</a-button>
      <a-button type="primary" @click="handleSave_" style="margin-left: 8px;" v-if="table.dataSource && table.dataSource.length">保存</a-button>
      <template v-if="table.dataSource && table.dataSource.length">
        <div style="margin-top: 10px;">
          <a-button icon="table" type="primary" @click="handleAddLine">添加尺码(行)</a-button>
          <a-button icon="table" type="primary" style="margin-left: 8px;" @click="handleAddRow">添加尺码(列)</a-button>
        </div>
        <j-vxe-table
          :key="keyNumber"
          style="margin-top: 20px;"
          class="j-vxe-table"
          ref="vTable"
          :loading="table.loading"
          :columns="table.columns"
          :dataSource="table.dataSource"
          :pagination="null"
        />
      </template>
    </a-row>
    <a-modal v-model="visible" title="列标题" @ok="handleOk" @cancel="handleTitleCancel">
      <a-form-model-item label="列标题" :labelCol="{xs: { span: 24 },sm: { span: 4 }}" :wrapperCol="wrapperCol">
        <a-input v-model.trim="rowTitle" placeholder="请输入列标题"  ></a-input>
      </a-form-model-item>
    </a-modal>
    <a-modal v-model="visible_" title="尺码表方案" @ok="handleSkuOk" @cancel="handleCancel">
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="方案名称" :labelCol="{xs: { span: 24 }, sm: { span: 4 }}" :wrapperCol="wrapperCol">
            <a-input v-model.trim="modelName" placeholder="请输入方案名称"  ></a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { postAction, getAction, deleteAction, putAction } from '@/api/manage'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
export default {
  name: 'SkuSizeChart',
  props: {
    model: {
      type: Object,
      default: () => {}
    },
    generateResult: {
      type: Object,
      default: () => {}
    }
  },
  data(){
    return {
      keyNumber: 0,
      visible: false,
      visible_: false,
      rowTitle: '',
      modelName: '',
      skuSizeTableSchemeId: '',
      skuSizeTableSchemeOptions: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      table: {
        // 是否正在加载
        loading: false,
        // 分页器参数
        pagination: {
          // 当前页码
          current: 1,
          // 每页的条数
          pageSize: 20,
          // 可切换的条数
          pageSizeOptions: ['10', '20', '30', '100', '200'],
          // 数据总数（目前并不知道真实的总数，所以先填写0，在后台查出来后再赋值）
          total: 0,
        },
        // 最后选中的行
        lastRow: null,
        // 选择的行
        selectedRows: [],
        // 数据源，控制表格的数据
        dataSource: [],
        // 列配置，控制表格显示的列
        columns: [],
      },
      url: {
        add: '/hzkj-product/product/productLibrary/skuSizeTableScheme/add',
        edit: "/hzkj-product/product/productLibrary/skuSizeTable/edit",
        queryById: "/hzkj-product/product/productLibrary/skuSizeTable/queryById",
        list: '/hzkj-product/product/productLibrary/skuSizeTableScheme/list',
        delete: '/hzkj-product/product/productLibrary/skuSizeTableScheme/delete'
      }
    }
  },
  watch: {
    generateResult: {
      immediate: true,
      handler(val){
        if(val && val.tableHeader && val.tableHeader.length){
          this.handleGenerateResult(this.generateResult);
        }
      }
    },
    model: {
      immediate: true,
      handler(val){
        if(val.id){
          this.getList();
        }
      }
    }
  },
  methods: {
    handleGenerateResult(generateResult){
      this.table.columns = generateResult.tableHeader && generateResult.tableHeader.map(item => {
        return {
          key: item.index,
          title: item.title,
          type: JVXETypes.input,
          placeholder: '请输入',
        }
      }) || [];
      this.table.dataSource = generateResult.tableData || [];
      this.keyNumber++;
    },
    handleAddLine(){
      let line = (this.table.dataSource && this.table.dataSource[0]) || {};
      let lineParam = {};
      Object.keys(line) && Object.keys(line).forEach(item => {
        lineParam[item] = '';
      })
      this.table.dataSource.push(lineParam);
      this.$message.success('添加成功!');
    },
    handleAddRow(){
      this.visible = true;
    },
    handleOk(){
      if(!this.rowTitle){
        this.$message.warning('请输入列标题！');
        return;
      }
      let key = new Date().getTime();
      this.table.columns.push({
        key,
        title: this.rowTitle,
        type: JVXETypes.input,
        placeholder: "请输入",
      })
      this.table.dataSource = this.table.dataSource.map(item => {
        return {
          ...item,
          key: ''
        }
      })
      this.$message.success('添加成功!');
      this.handleTitleCancel();
      this.keyNumber++;
    },
    handleTitleCancel(){
      this.rowTitle = '';
      this.visible = false;
    },
    handleSave(){
      if(!(this.table.dataSource && this.table.dataSource.length)){
        this.$message.warning('请生成尺码表！');
        return;
      }
      this.visible_ = true;
    },
    handleSkuOk(){
      if(!this.modelName){
        this.$message.warning('请输入方案名称！');
        return;
      }
      let tableData = this.$refs.vTable.getTableData();
      tableData = tableData.filter(item => {
        let values = Object.values(item);
        values = values.filter(cur => cur);
        return values.length > 1;
      })
      tableData = JSON.stringify(tableData);
      let tableHeader = this.table.columns.map(item => {
        return {
          index: item.key,
          title: item.title
        }
      })
      tableHeader = JSON.stringify(tableHeader);
      let params = {
        skuId: this.model.id,
        name: this.modelName,
        tableHeader,
        tableData
      }
      postAction(this.url.add, params).then((res) => {
        if(res.success){
          this.$message.success(res.message);
          this.getList();
          this.handleCancel();
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    handleCancel(){
      this.visible_ = false;
      this.modelName = '';
    },
    getList(){
      getAction(this.url.list, { skuId: this.model.id }).then((res) => {
        if(res.success){
          let skuSizeTableSchemeOptions = (res.result && res.result.records) || [];
          this.skuSizeTableSchemeOptions = skuSizeTableSchemeOptions.map(item => {
            return {
              ...item,
              text: item.name,
              value: item.id
            }
          })
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    handleDelete(){
      if(!this.skuSizeTableSchemeId){
        this.$message.warning('请选择要删除的尺码表方案！');
        return;
      }
      deleteAction(this.url.delete, { id: this.skuSizeTableSchemeId }).then((res) => {
        if(res.success){
          this.$message.success(res.message);
          this.getList();
          this.skuSizeTableSchemeId = '';
          this.table.dataSource = [];
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    handleChange(val){
      if(!val){
        this.table.columns = [];
        this.table.dataSource = [];
        this.keyNumber++;
        return;
      }
      let generateResult = [...this.skuSizeTableSchemeOptions];
      generateResult = generateResult.find(item => item.id === val);
      if(!Array.isArray(generateResult.tableHeader)){
        generateResult.tableHeader = generateResult.tableHeader ? JSON.parse(generateResult.tableHeader) : [];
      }
      if(!Array.isArray(generateResult.tableData)){
        generateResult.tableData = generateResult.tableData ? JSON.parse(generateResult.tableData) : [];
      }
      this.table.columns = generateResult.tableHeader && generateResult.tableHeader.map(item => {
        return {
          key: item.index,
          title: item.title,
          type: JVXETypes.input,
          placeholder: '请输入',
        }
      }) || [];
      this.table.dataSource = generateResult.tableData || [];
      this.keyNumber++;
    },
    handleSave_(){
      let tableData = this.$refs.vTable.getTableData();
      tableData = tableData.filter(item => {
        let values = Object.values(item);
        values = values.filter(cur => cur);
        return values.length > 1;
      })
      tableData = JSON.stringify(tableData);
      let tableHeader = this.table.columns.map(item => {
        return {
          index: item.key,
          title: item.title
        }
      })
      tableHeader = JSON.stringify(tableHeader);
      let params = {
        skuId: this.model.id,
        tableHeader,
        tableData
      }
      putAction(this.url.edit, params).then((res) => {
        if(res.success){
          this.$message.success(res.message);
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    getSizeTable(){
      return new Promise((resolve, reject) => {
        if(this.table.dataSource && this.table.dataSource.length){
          this.$refs.vTable.validateTable().then(errMap => {
            if(!errMap){
              let tableData = this.$refs.vTable.getTableData();
              tableData = tableData.filter(item => {
                let values = Object.values(item);
                values = values.filter(cur => cur);
                return values.length > 1;
              })
              tableData = JSON.stringify(tableData);
              let tableHeader = this.table.columns.map(item => {
                return {
                  index: item.key,
                  title: item.title
                }
              })
              tableHeader = JSON.stringify(tableHeader);
              this.model.sizeTable = {
                ...this.generateResult,
                tableData,
                tableHeader
              }
              resolve();
            }
          })
        }else{
          resolve();
        }
      })
    }
  }
}
</script>